import {
  Button,
  Form,
  FormProps,
  Input,
  Modal,
  Select,
  Space,
  Switch,
  Table,
  TablePaginationConfig,
  message
} from 'antd'
import type { Permissions, User } from '@/types/index'
import React, { useEffect, useState } from 'react'

import PubSub from 'pubsub-js'
import Remove from '@/components/Remove'
import useCrud from '@/api/CRUD/useCrud'
import { useUpStatus } from '@/api/query'

interface searchInterface {
  username: string
  email: string
  phone: string
}

type FieldType = {
  username?: string
  password?: string
  phone?: string
  email?: string
  permissionsId?: string[]
  status?: boolean
  addTime?: Date
  lastLogin?: Date
}

/* eslint-disable react-hooks/rules-of-hooks */

const { Column } = Table

const index: React.FC = () => {
  const [form] = Form.useForm()
  // 搜索条件
  const [searchData, setSearchData] = useState<searchInterface>({
    username: '',
    phone: '',
    email: ''
  })
  const [searchParams, setSearchParams] = useState<searchInterface>()
  // 导入自定义Hooks
  const { useCreateItem, useUpdateItem, useItems } = useCrud()
  const [messageApi, contextHolder] = message.useMessage()
  // 选择的角色ID
  const [id, setId] = useState('')
  // 页码
  const [pageNum, setPageNum] = useState(1)
  // 每页条数
  const [pageSize, setPageSize] = useState(8)
  // 数据请求
  const { isError, isLoading, data, isFetching } = useItems(
    '/permissions/getUser',
    pageNum,
    pageSize,
    searchParams
  )
  const [userData, setUserData] = useState<User[]>([])
  const [localStatus, setLocalStatus] = useState<{ [key: string]: boolean }>({})
  // 过滤数据赋予key值
  useEffect(() => {
    if (data) {
      const dataSource = data?.userData.map((item: User) => ({
        ...item,
        key: item._id
      }))
      setUserData(dataSource)
    }
    const PermissionsData = data?.PermissionsData.map((item: any) => ({
      value: item._id,
      label: item.RoleName
    }))
    setPermissionsData(PermissionsData)
  }, [data])
  if (isLoading && !isFetching) {
    return <div>Loding...</div>
  }
  if (isError) {
    return <div>Error...</div>
  }
  const [status, setStatus] = useState(false)
  // 用户启用状态的调用
  const { mutate: mutateStatus } = useUpStatus(id, status)
  // 修改启用状态
  const statusChange = async (id: string, status: boolean) => {
    setId(id)
    const newStatus = !status
    setLocalStatus((prev) => ({ ...prev, [id]: newStatus }))
    setStatus(!status)
    await mutateStatus()
    if (status) {
      messageApi.open({
        type: 'success',
        content: '成功禁用'
      })
    } else {
      messageApi.open({
        type: 'success',
        content: '成功启用'
      })
    }
  }
  // 发布状态
  const publishMessage = () => {
    PubSub.publish('change', '去后端拿数据')
  }
  // 页码改变触发
  const onChange = (pagination: TablePaginationConfig) => {
    setPageNum(pagination.current as number)
    setPageSize(pagination.pageSize as number)
  }
  // 控制分配角色
  const [open, setOpen] = useState(false)
  const showModal = (data: User) => {
    setOpen(true)
    setId(data._id)
    const roleList: string[] = []
    data.permissionsId.forEach((item: Permissions) => {
      roleList.push(item._id)
    })
    setRoleList(roleList)
  }
  const { mutate: mutateRoles } = useUpdateItem(
    '/permissions/updatePermissions'
  )
  // 确定分配
  const handleOk = () => {
    mutateRoles({ id, data: roleList })
    setOpen(false)
    publishMessage()
  }
  // 选择的角色权限ID列表
  const [roleList, setRoleList] = useState<string[]>([])
  // 角色列表
  const [PermissionsData, setPermissionsData] = useState([''])
  // 分配角色
  const handleChange = (value: string[]) => {
    setRoleList(value)
  }
  const { mutate: addMutate } = useCreateItem('/permissions/addUser')
  // 添加用户
  const [addFlag, setAddFlag] = useState(false)
  const onFinish: FormProps<FieldType>['onFinish'] = (values: FieldType) => {
    addMutate(values)
    form.resetFields()
  }
  // 搜索
  const searchSubmit = () => {
    setSearchParams(searchData)
  }
  return (
    <div>
      {contextHolder}
      <Button type="primary" onClick={() => setAddFlag(true)}>
        添加用户
      </Button>
      <div>
        <span>账号：</span>
        <Input
          style={{ width: 200 }}
          value={searchData.username}
          onChange={(e) => {
            setSearchData({
              ...searchData,
              username: e.target.value
            })
          }}
        />
        <span>手机号：</span>
        <Input
          style={{ width: 200 }}
          value={searchData.phone}
          onChange={(e) => {
            setSearchData({
              ...searchData,
              phone: e.target.value
            })
          }}
        />
        <span>邮箱：</span>
        <Input
          style={{ width: 200 }}
          value={searchData.email}
          onChange={(e) => {
            setSearchData({
              ...searchData,
              email: e.target.value
            })
          }}
        />
        <Button type="primary" onClick={searchSubmit}>
          搜索
        </Button>
      </div>
      <Table<User>
        dataSource={userData}
        pagination={{
          current: pageNum,
          pageSize: pageSize,
          total: 22
        }}
        onChange={(pagination) => onChange(pagination)}
      >
        <Column
          title="编号"
          key="firstName"
          render={(_: any, record: User) => (
            <span>{record._id.slice(10, 12)}</span>
          )}
        />
        <Column title="账号" dataIndex="username" key="username" />
        <Column title="手机号" dataIndex="phone" key="phone" />
        <Column title="邮箱" dataIndex="email" key="email" />
        <Column
          title="注册时间"
          key="addTime"
          render={(_: any, record: User) => (
            <span>{new Date(record.addTime).toLocaleString()}</span>
          )}
        />
        <Column
          title="最后登录时间"
          key="lastLogin"
          render={(_: any, record: User) => (
            <span>{new Date(record.lastLogin).toLocaleString()}</span>
          )}
        />
        <Column
          title="是否启用"
          key="status"
          render={(_: any, record: User) => (
            <Switch
              checked={
                localStatus[record._id] !== undefined
                  ? localStatus[record._id]
                  : record.status
              }
              onChange={() => statusChange(record._id, record.status)}
            />
          )}
        />
        <Column
          title="操作"
          key="action"
          render={(_: any, record: User) => (
            <Space size="middle">
              <Button onClick={() => showModal(record)} type="primary">
                分配角色
              </Button>
              <Remove id={record._id} path="permissions/delUser"></Remove>
            </Space>
          )}
        />
      </Table>
      {/* 分配角色弹出框 */}
      <Modal
        open={open}
        title="分配角色"
        onCancel={() => setOpen(false)}
        footer={[
          <Button key="no" onClick={() => setOpen(false)}>
            取消
          </Button>,
          <Button key="yes" onClick={handleOk} type="primary">
            确定
          </Button>
        ]}
      >
        <div style={{ height: '15vh', display: 'flex', alignItems: 'center' }}>
          <Select
            mode="multiple"
            allowClear
            style={{ width: '70%' }}
            placeholder="请选择角色"
            onChange={handleChange}
            options={PermissionsData}
            value={roleList}
          />
        </div>
      </Modal>
      {/* 添加用户弹出框 */}
      <Modal
        open={addFlag}
        title="添加用户"
        footer={[
          <Button key="no" onClick={() => setAddFlag(false)}>
            取消
          </Button>
        ]}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          onFinish={onFinish}
        >
          <Form.Item<FieldType> label="账号" name="username">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="密码" name="password">
            <Input.Password />
          </Form.Item>
          <Form.Item<FieldType> label="邮箱" name="email">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="手机号" name="phone">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="是否启用" name="status">
            <Switch />
          </Form.Item>
          <Form.Item<FieldType> label="用户角色" name="permissionsId">
            <Select
              mode="multiple"
              allowClear
              style={{ width: '70%' }}
              placeholder="请选择角色"
              value={roleList}
              options={PermissionsData}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default index
